<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cartInfo in CartList" :key="cartInfo.id">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="cartInfo.isChecked === 1"
              @click="checkCart(cartInfo, $event)">
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl">
            <div class="item-msg">{{ cartInfo.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="ChangeGoodsNum('dec', cartInfo, $event)">-</a>
            <input autocomplete="off" type="text" :value="cartInfo.skuNum" minnum="1" class="itxt"
              @change="ChangeGoodsNum('inp', cartInfo, $event)">

            <a href="javascript:void(0)" class="plus" @click="ChangeGoodsNum('inc', cartInfo, $event)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a href="#none" class="sindelet" @click="delOneGoods(cartInfo.skuId)">删除</a>
            <br>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool"  v-show="CartList.length">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" @click="batchCheckCart" :checked="isAll">
        <span>全选</span>
      </div>
      <div class="option">
        <a href="#none" @click="BatchDelGoods">删除选中的商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{ total }}</span>件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ GoodsTotalNum }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade" >结算</router-link>
        </div>
      </div>
    </div>
    <div class="empty" v-show="!CartList.length">
      <h2>购物车空空如也</h2>
      <img src="http://49.232.112.44/img/empty.751bed26.gif" alt="" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'ShopCart',
}

</script>

<script setup>
import { throttle } from 'lodash'
import { ref, onMounted, computed } from 'vue'
import { regGoodsNum } from '../../utils/regexp'
import {
  reqCartList,
  reqCheCart,
  reqBatchCheck,
  reqDelOneGoods,
  reqBatchDelGoods
} from '../../api/ShopCart'

import { reqShoppingcar } from '../../api/Detail'
const CartList = ref([])
// const isAll = ref("")
const getCartLsit = async () => {
  const result = await reqCartList()
  // console.log('aaa', result)
  CartList.value = result.data[0]?.cartInfoList || [];

}
// 单选切换状态
const checkCart = async (cartInfo, e) => {
  const id = cartInfo.skuId
  const target = e.target.checked ? 1 : 0
  // 发送请求
  const result = await reqCheCart(id, target)
  if (result.code === 200) {
    cartInfo.isChecked = target
  } else {
    alert('切换商品状态失败')
  }
}

// 切换全选状态
const batchCheckCart = async (e) => {
  let target = e.target.checked ? 1 : 0
  // cardId 得到一个当前用户购物车的所以数据的ID
  const cardId = CartList.value.map((cart) => cart.skuId)
  // 发送请求
  const result = await reqBatchCheck(target, cardId)
  // console.log("hehe",result)
  if (result.code === 200) {
    CartList.value.forEach((item) => {
      item.isChecked = target
    })
  } else {
    alert('全选修改失败')
  }
}
// 切换全选状态
const isAll = computed(() => {
  return CartList.value.every((item) => item.isChecked === 1)
})
// 删除单个商品
const delOneGoods = async (id) => {
  if (!confirm("确定删除吗？")) return
  const result = await reqDelOneGoods(id)
  // console.log(result)
  if (result.code === 200) {
    CartList.value = CartList.value.filter((item) => item.skuId !== id);
    alert('删除商品成功')
  } else {
    alert('删除商品失败')
  }
}

// 点击删除选中的商品
const BatchDelGoods = async () => {
  if (!confirm('确定删除选中的商品吗？')) return;
  // 收集选中的id 
  let ids = []
  CartList.value.forEach((item) => {
    if (item.isChecked) {
      // 如果是选中的那么就将选中的id放到数组中
      ids.push(item.skuId)
    }
  })
  const result = await reqBatchDelGoods(ids)
  if (result.code === 200) {
    CartList.value = CartList.value.filter((item) => !item.isChecked)
    alert('删除选中商品成功')
  } else {
    alert('删除选中的商品失败')
  }
}


// 修改商品数量
const ChangeGoodsNum = throttle(async (type, cartInfo, e) => {
  switch (type) {
    case 'inp':
      // 判断用户输入是否正确
      const value = e.target.value.trim()
      // console.log("ccccc",e.target.value)
      //利用正则校验
      if (regGoodsNum.test(value)) {
        const num = value - cartInfo.skuNum
        const result = await reqShoppingcar(cartInfo.skuId, num)
        if (result.code === 200) {
          // 修改成功后，修改本地数据，*1是为了将字符串转化为数字
          cartInfo.skuNum = value * 1
          // 为选中状态
          cartInfo.isChecked = 1
        } else {
          alert("修改数据失败");
          //将数据回复成为用户输入之前的值
          e.target.value = cartInfo.skuNum;
          
        }
      } else {
        // 校验不通过
        alert('请输入1-200之间的整数')
        e.target.value = cartInfo.skuNum;
      }
      break;
    case 'inc':
      if (cartInfo.skuNum === 200) {
        return alert('最多只能购买200个')
      } else {
        const result = await reqShoppingcar(cartInfo.skuId, 1)
        if (result.code === 200) {
          cartInfo.skuNum++
          cartInfo.isChecked = 1
        } else {
          alert('增加商品数量失败')
        }
      }
      break;
    case 'dec':
      if (cartInfo.skuNum === 1) {
        return alert('最少一个')
      } else {
        const result = await reqShoppingcar(cartInfo.skuId, -1)
        if (result.code === 200) {
          cartInfo.skuNum--
          cartInfo.isChecked = 1
        } else {
          alert('减少商品失败')
        }
      }
      break;
  }
}, 500, { throttle: false })


// 计算商品总数量
const total = computed(() => {
  let n = 0
  CartList.value.forEach((item) => {
    if (item.isChecked) {
      n += item.skuNum
    }
  })
  return n
})

// 计算商品总价格
const GoodsTotalNum = computed(() => {
  let n = 0
  CartList.value.forEach((item) => {
    if (item.isChecked) {
      n += item.skuNum * item.skuPrice;
    }
  })
  return n
})


onMounted(() => {
  getCartLsit()
})






</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      &>div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        &>li {
          float: left;
        }

        .cart-list-con1 {
          width: 15%;
        }

        .cart-list-con2 {
          width: 35%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con4 {
          width: 10%;
        }

        .cart-list-con5 {
          width: 17%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 31px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }


      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
          text-decoration: none;

          &hover {
            color: white !important;
          }
        }
      }
    }
  }
}
.empty {
  padding: 20px;
  text-align: center;
  h2 {
    color: gray;
  }
  img {
    width: 300px;
  }
}
</style>